package jdbc.batch_;

import jdbc.utils.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//演示java的批处理
public class Batch_ {
    //传统方法，添加5000条数据到admin2
    @Test
    public void noBatch() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin values(?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start = System.currentTimeMillis();//开始时间
        for (int i = 0; i < 5000; i++) {//5000执行
            preparedStatement.setString(1,"smith"+i);
            preparedStatement.setString(2,"000000");
            preparedStatement.executeUpdate();
        }
        long end = System.currentTimeMillis();
        System.out.println("传统的方式 耗时="+(end - start));//传统的方式 耗时7587
        //关闭连接
        JDBCUtils.closConnection(null,connection,preparedStatement);
    }

    //使用批量方式添加数据
    @Test
    public void batch() throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin values(?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1,"smith"+i);
            preparedStatement.setString(2,"000000");
            //将sql 语句加入到批处理包中
            preparedStatement.addBatch();
            //当有1000条记录时，在批量执行
            if((i+1)%1000 == 0){
            preparedStatement.executeBatch();
            //清空
            preparedStatement.clearBatch();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("传统的方式 耗时="+(end - start));//批量方式 耗时85
        //关闭连接
        JDBCUtils.closConnection(null,connection,preparedStatement);
    }
}
